package bdhub.littletail.lib.net.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.File;

import bdhub.littletail.app.LittleTailApplication;
import bdhub.littletail.lib.config.CConfig;
import bdhub.littletail.lib.net.listener.OnResponseListener;
import bdhub.littletail.lib.net.request.JsonRequest;
import bdhub.littletail.lib.net.volley.Request;
import bdhub.littletail.lib.net.volley.RequestQueue;
import bdhub.littletail.lib.net.volley.toolbox.HttpStack;
import bdhub.littletail.lib.net.volley.toolbox.Volley;
import bdhub.littletail.lib.utils.FileUtils;
import bdhub.littletail.lib.utils.common.CThreadUtils;

/**
 * Created by Freddy on 2016/2/23.
 * chenshichao@outlook.com
 */
public class NetworkManager {

    private static RequestQueue REQUEST_QUEUE;
    /**
     * 设置是否使用静态数据来测试，不连接服务器<br />
     * true 使用本地假数据<br />
     * false 使用服务器数据<br />
     */
    private static final boolean USE_STITC_DATA_TEST = false;

    /**
     * 单实例
     */
    private static synchronized RequestQueue getInstance() {
        if (null == REQUEST_QUEUE) {
            synchronized (NetworkManager.class) {
                if (null == REQUEST_QUEUE) {
                    HttpStack httpStack = USE_STITC_DATA_TEST ? new TestHttpStack() : null;
                    REQUEST_QUEUE = Volley.newRequestQueue(LittleTailApplication.sharedInstance(), httpStack);
                }
            }
        }
        return REQUEST_QUEUE;
    }

    /**
     * 发送一个请求<br />
     * 默认使用缓存
     *
     * @param request
     */
    public static <T> void sendRequest(final Request<T> request) {
        CThreadUtils.runInBackground(new Runnable() {

            @Override
            public void run() {
                getInstance().add(request);
            }
        });
    }

    /**
     * 发送一个请求
     *
     * @param request
     * @param useCache 是否使用缓存
     */
    public static <T> void sendRequest(final Request<T> request,final boolean useCache) {
        CThreadUtils.runInBackground(new Runnable() {

            @Override
            public void run() {
                request.setShouldCache(useCache);
                getInstance().add(request);
            }
        });
    }

    /**
     * 发送一个 JSON 请求（不使用缓存）
     *
     * @param function 	接口名
     * @param params	参数
     * @param listener	回调监听
     */
    public static <T> void sendRequest(final String function, final Object params, final OnResponseListener<JSONObject> listener) {
        CThreadUtils.runInBackground(new Runnable() {

            @Override
            public void run() {
                JsonRequest request = new JsonRequest(function, params, listener);
                request.setShouldCache(false);
                getInstance().add(request);
            }
        });
    }


    public static synchronized void release() {
        if (null != REQUEST_QUEUE) {
            REQUEST_QUEUE.stop();
            clearCache();
            REQUEST_QUEUE = null;
        }
    }

    private static void clearCache() {
        try {
            REQUEST_QUEUE.getCache().clear();
            File file = FileUtils.getCacheFolder(CConfig.NETWORK_CHACHE_FOLDER);
            if (null != file && file.isDirectory()) {
                File[] childFiles = file.listFiles();
                if (childFiles != null && childFiles.length > 0) {
                    for (int i = 0; i < childFiles.length; i++) {
                        childFiles[i].delete();
                    }
                }
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
